package com.eshop.we.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.eshop.we.business.UserBusiness;
import com.eshop.we.constants.BaseConstants;
import com.eshop.we.result.Result;
import com.eshop.we.user.entity.User;
import com.eshop.we.utils.*;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Api(value = "微信接口管理", description = "微信接口管理")
@RestController
@RequestMapping("/wxauto")
public class WxMaUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMaService wxService;

    @Autowired
    private UserBusiness userBusiness;

    @Autowired
    private RedisUtil redis;

    @Autowired
    private CookieUtil cookieUtil;

    /**
     * 登陆接口
     */
    @ApiOperation(value = "微信授权登录接口",notes = "不拦截")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "code",
                    required = true,
                    dataType = "string",
                    paramType = "query",
                    value = "XwgfGKSFLLVsfllxmwkjapl",
                    allowableValues = "",
                    allowMultiple = false
            )
    })
    @ApiResponses({
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
            @ApiResponse(code=1000,message="微信code为空"),
            @ApiResponse(code=1001,message="微信授权失败")
    })
    @GetMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true) String code)throws Exception {
        if (StringUtils.isBlank(code)) {
            return new Result(BaseConstants.WX_CODE_NULL,"code为空！","null");
        }
            WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            this.logger.info(session.getUnionid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            if(session==null){
                return  new Result(BaseConstants.WX_AUTO_ERROR,"授权失败！",null);
            }
            redis.set("sessionKey",session.getSessionKey());
            String openId= session.getOpenid();
            User user= userBusiness.selectOne( new EntityWrapper<User>().eq("open_id", openId));
            if(user==null){
                user.setOpenId(openId);
                userBusiness.insert(user);
            }
            String token= DesUtil.getInstance().encrypt(BaseConstants.TOKEN_PREFIX+","+openId+","+BaseConstants.TOKEN_SUYFFI);
            user=  userBusiness.selectOne(new EntityWrapper().eq("open_id",openId));
            String tokenId= MD5Utils.encode(user.getId()+"eshop"+user.getCtime());
            redis.set(tokenId,token,60*60*24*30*6);
            cookieUtil.addCookieUser(response,tokenId);
            user.setLoginToken(token);
            return  Result.success(userBusiness.updateById(user));
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/userinfo")
    public Result info(HttpServletRequest request, @RequestParam("signature")String signature, @RequestParam("rawData")String rawData, @RequestParam("encryptedData")String encryptedData, @RequestParam("iv")String iv) {
        String sessionKey=(String) request.getSession().getAttribute("sessionKey");
        // 用户信息校验
        if (!this.wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return new Result(BaseConstants.USER_CHECK_ERROR,"用户信息校验失败！",null);
        }
        // 解密用户信息
        WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        return  Result.success(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(String sessionKey, String signature, String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!this.wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = this.wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(phoneNoInfo);
    }

}
